package com.property.manage.util;

import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import com.guardchina.framework.util.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/9/17
 */
@Slf4j
public class ExportUtil {

    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, XSSFWorkbook wb){
        try {
            log.info("导出文件名：" + fileName);
            final String userAgent = request.getHeader("USER-AGENT");
            String finalFileName = null;

            if (StringUtils.contains(userAgent, "Edge")) {
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            } else if (StringUtils.contains(userAgent, "MSIE")) {
                // IE浏览器
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            } else if (StringUtils.contains(userAgent, "Mozilla")) {
                // google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                // 其他浏览器
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            }

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + finalFileName);
            response.setCharacterEncoding("utf-8");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            throw new BusinessException("导出excel失败", e);
        }
    }
}
